<template>
  <div class="content-wrapper">
    <!-- <div class="content-header">用户管理</div> -->
    <div class="content-container">
      <el-form
        :inline="true"
        :model="listQuery"
        :rules="rules"
        class="filter-container"
      >
        <el-form-item label="登录名" prop="userCode">
          <el-input
            v-model.trim="listQuery.userCode"
            placeholder="登录名"
            class="filter-item"
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            v-waves
            class="filter-item"
            size="small"
            round
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >
            搜索
          </el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="listLoading"
        :data="list"
        highlight-current-row
        :cell-class-name="changeCellStyle"
        height="500"
      >
        <el-table-column label="状态" prop="status" width="60px">
          <template slot-scope="{ row }">
            <span>{{ renderStatus(row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="登录名" prop="userCode" width="120px" />
        <el-table-column label="名字" prop="userName" min-width="120px">
          <template slot-scope="{ row }">
            {{ row.userName }}
            <el-badge v-if="userId === row.userId" value="本人" />
          </template>
        </el-table-column>
        <el-table-column label="头像" prop="avatar" align="center" width="80px">
          <template slot-scope="{ row }">
            <el-avatar :size="40" :src="row.avatar">
              <img
                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
              />
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" width="120px" />
        <el-table-column label="邮箱" prop="email" min-width="150px" />
        <el-table-column label="部门" min-width="150px">
          <template slot-scope="{ row }">
            <span v-if="row.userGroup !== null">{{ row.userGroup.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色" min-width="150px">
          <template slot-scope="{ row }">
            <span v-if="row.roleList !== null">{{
              renderRole(row.roleList)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="150px">
          <template slot="header" slot-scope="scope">
            <span>初始密码</span>
            <i
              class="el-icon-view"
              style="margin-left: 5px"
              @click="changePasswordState"
            ></i>
          </template>

          <template slot-scope="{ row }">
            <span v-if="passwordState">{{ row.initialPassword }}</span>
            <span v-else>******</span>
            
            <!-- <el-input
              placeholder="请输入密码"
              v-model="row.initialPassword"
              show-password
            /> -->
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="280px"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button
              type="text"
              size="mini"
              @click="onOff(row)"
              v-if="
                roles[0] === 'admin' &&
                userId !== row.userId &&
                row.userCode !== 'admin'
              "
            >
              <span v-if="row.status == 0">禁闭</span>
              <span v-else>正常</span>
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="handleUpdatePosition(row)"
            >
              岗位信息
            </el-button>
             <el-button
              type="text"
              size="mini"
              @click="handleUpdateName(row)"
            >
              修改用户名称
            </el-button>
            <el-button
              v-if="userId !== row.userId && roles[0] === 'admin'"
              type="text"
              size="mini"
              @click="handleUpdateRole(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="handleUpdateUserGroup(row)"
            >
              设置公司/部门
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page-number.sync="listQuery.pageNumber"
        :page-size.sync="listQuery.pageSize"
        @pagination="getList"
      />

      <el-drawer title="分配角色" :visible.sync="dialogFormVisible">
        <el-form
          ref="dataForm"
          :model="temp"
          label-position="right"
          label-width="120px"
          style="width: 480px"
        >
          <el-form-item label="角色（多选）">
            <el-select
              :key="isRoleIdShow"
              v-model="temp.roleIdList"
              multiple
              class="filter-item"
              placeholder="请选择"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateRole()">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

      <el-drawer
        title="设置公司/部门"
        :visible.sync="userGroupDialogFormVisible"
      >
        <el-form
          ref="userGroupDataForm"
          :model="userGroupModel"
          label-position="right"
          label-width="120px"
          style="width: 480px"
        >
          <el-form-item label="隶属公司/部门">
            <el-cascader
              :key="isUserGroupCascaderShow"
              v-model="selectedUserGroupId"
              :options="userGroupOptions"
              :props="{ checkStrictly: true }"
              filterable
              clearable
              @change="handleUserGroupIdChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateUserGroup()"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </el-drawer>

      <el-drawer title="岗位信息" :visible.sync="positionDialogFormVisible">
        <el-form
          ref="positionForm"
          :model="positionModel"
          :rules="positionRules"
          label-position="right"
          label-width="120px"
          style="width: 480px"
        >
          <el-form-item label="员工编号" prop="employeeCode">
            <el-input v-model="positionModel.employeeCode" />
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="positionModel.name" />
          </el-form-item>
          <el-form-item label="英文名">
            <el-input v-model="positionModel.englishName" />
          </el-form-item>
          <el-form-item label="职位">
            <el-input v-model="positionModel.jobTitle" />
          </el-form-item>
          <el-form-item label="员工关系" prop="relationship">
            <el-select v-model="positionModel.relationship">
              <el-option
                v-for="item in relationship"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入职日期">
            <el-date-picker
              v-model="positionModel.entryDate"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="转正日期">
            <el-date-picker
              v-model="positionModel.regularDate"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="离职日期">
            <el-date-picker
              v-model="positionModel.resignDate"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="学历">
            <el-select v-model="positionModel.education">
              <el-option
                v-for="item in education"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="毕业院校">
            <el-input v-model="positionModel.school" />
          </el-form-item>
          <el-form-item label="专业">
            <el-input v-model="positionModel.speciality" />
          </el-form-item>
          <el-form-item label="证书">
            <el-input v-model="positionModel.certificate" />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="positionModel.identification" />
          </el-form-item>
          <el-form-item label="生日">
            <el-date-picker
              v-model="positionModel.birthday"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="户口性质">
            <el-select v-model="positionModel.registrationType">
              <el-option
                v-for="item in registrationType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="户籍所在地">
            <el-input v-model="positionModel.registrationAddress" />
          </el-form-item>
          <el-form-item label="银行卡">
            <el-input v-model="positionModel.bankCard" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updatePosition()">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>

      <el-drawer
        title="修改名称"
        :visible.sync="nameDialogFormVisible"
      >
        <el-form
          ref="nameDataForm"
          :model="nameModel"
          label-position="right"
          label-width="120px"
          style="width: 480px"
        >
          <el-form-item label="名字" >
            <el-input v-model="nameModel.userName" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="updateName()"
              >提交</el-button
            >
          </el-form-item>
        </el-form>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  listUser,
  updateUserRole,
  listRoleId,
  saveUserGroupUser,
  getUserGroupId,
  lock,
  updateUser
} from '@/api/uc/user'
import { listRoleItem } from '@/api/uc/role'
import { listUserGroupTreeItemForManage } from '@/api/uc/userGroup'
import { findAndAccept3 } from '@/utils/tree'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { getUserId, save } from '@/api/uc/search.js'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNumber: 1,
        pageIndex: 0,
        pageSize: 20,
        type: 1,
        userCode: '',
        withUserGroup: true,
        withRole: true
      },
      temp: {
        userId: null,
        roleIdList: []
      },
      isRoleIdShow: '0',
      roleOptions: null,
      dialogFormVisible: false,
      userGroupModel: {
        userId: null,
        userGroupId: null
      },
      userGroupOptions: null,
      selectedUserGroupId: [],
      isUserGroupCascaderShow: '0',
      userGroupDialogFormVisible: false,
      rules: {
        userCode: [
          {
            pattern: /^[a-zA-Z0-9_-]+$/,
            message: '登录名由a-zA-Z0-9_-等字母组成',
            trigger: 'change'
          }
        ]
      },
      positionDialogFormVisible: false,
      positionModel: {},
      positionRules: {
        employeeCode: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        englishName: [{ required: true, message: '不能为空', trigger: 'blur' }],
        relationship: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        entryDate: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      relationship: [
        {
          value: '1',
          label: '在职'
        },
        {
          value: '2',
          label: '临时'
        },
        {
          value: '4',
          label: '离职'
        }
      ],
      education: [
        {
          value: '1',
          label: '小学'
        },
        {
          value: '2',
          label: '初中'
        },
        {
          value: '3',
          label: '中专'
        },
        {
          value: '5',
          label: '大专'
        },
        {
          value: '6',
          label: '本科'
        },
        {
          value: '4',
          label: '高中'
        },
        {
          value: '7',
          label: '硕士'
        },
        {
          value: '8',
          label: '博士'
        }
      ],
      registrationType: [
        {
          value: '1',
          label: '农业'
        },
        {
          value: '8',
          label: '城镇'
        }
      ],
      userIds: '',
      userCode: '',
      passwordState: false,
      nameDialogFormVisible:false,
      nameModel:{
        userName:null,
        userId:null,
      },
    }
  },
  computed: {
    ...mapGetters(['userId', 'roles', 'userName'])
  },
  created() {
    this.getList()
  },
  methods: {
    changeCellStyle({ row, column, rowIndex, columnIndex }) {
      if (
        (columnIndex === 6 && row.userGroup === null) ||
        (columnIndex === 7 && row.roleList === null)
      ) {
        return 'backWarning'
      }
    },
    getList() {
      this.listQuery.pageIndex = this.listQuery.pageNumber - 1
      this.listLoading = true
      listUser(this.listQuery).then((response) => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    renderStatus(status) {
      if (status === 0) {
        return '正常'
      } else {
        return '禁闭'
      }
    },
    renderRole(roleList) {
      const a = []
      roleList.forEach((e) => {
        a.push(e.name)
      })
      return a.toString()
    },
    setRoleIdList() {
      ++this.isRoleIdShow
      listRoleId({ userId: this.temp.userId }).then((res) => {
        this.temp.roleIdList = res.data
      })
    },
    handleUpdateRole(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogFormVisible = true
      if (this.roleOptions === null) {
        listRoleItem({ typeList: null }).then((res) => {
          this.roleOptions = res.data
          this.setRoleIdList()
        })
      } else {
        this.setRoleIdList()
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateRole() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUserRole(tempData).then(() => {
            this.handleFilter()
            this.dialogFormVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          })
        }
      })
    },
    resetUserGroupModel() {
      this.userGroupModel = {
        userId: null,
        userGroupId: null
      }
    },
    handleUserGroupIdChange(value) {
      if (value) {
        this.userGroupModel.userGroupId = value[value.length - 1]
      }
    },
    clearUserGroupCascader() {
      this.selectedUserGroupId.length = 0
      ++this.isUserGroupCascaderShow
    },
    setUserGroupId() {
      getUserGroupId({ userId: this.userGroupModel.userId }).then((res) => {
        this.userGroupModel.userGroupId = res.data
        const parentStack = findAndAccept3(
          this.userGroupOptions,
          (e) => this.userGroupModel.userGroupId === e.value,
          (e) => {}
        )
        const a = []
        parentStack.forEach((node) => {
          a.push(node.value)
        })
        this.selectedUserGroupId = a
      })
    },
    handleUpdateUserGroup(row) {
      this.userGroupModel = Object.assign({}, row) // copy obj
      this.clearUserGroupCascader()
      this.userGroupDialogFormVisible = true
      if (this.userGroupOptions === null) {
        listUserGroupTreeItemForManage({ parentUserGroupId: null }).then(
          (response) => {
            this.userGroupOptions = response.data
            this.setUserGroupId()
          }
        )
      } else {
        this.setUserGroupId()
      }
      this.$nextTick(() => {
        this.$refs['userGroupDataForm'].clearValidate()
      })
    },
    updateUserGroup() {
      this.$refs['userGroupDataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.userGroupModel)
          saveUserGroupUser(tempData).then(() => {
            this.handleFilter()
            this.userGroupDialogFormVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          })
        }
      })
    },
    handleUpdatePosition(row) {
      this.positionDialogFormVisible = true
      this.userIds = row.userId
      this.userCode = row.userCode
      getUserId({ userId: row.userId }).then((res) => {
        if (res.code == 1) {
          console.log(res.data == null, 'oooo')
          if (res.data == null) {
            this.positionModel = {}
          } else {
            this.positionModel = res.data
          }
        }
      })
    },
    handleUpdateName(row) {
      this.nameDialogFormVisible = true
      this.nameModel.userName = row.userName
      this.nameModel.userId = row.userId
    },
    updatePosition() {
      this.$refs['positionForm'].validate((valid) => {
        if (valid) {
          let data = this.positionModel
          data.userId = this.userIds
          data.userCode = this.userCode
          save(data).then((res) => {
            if (res.code == 1) {
              this.$message.success('保存成功')
              this.positionModel = {}
              this.positionDialogFormVisible = false
            }
          })
        }
      })
    },
    updateName() {
      const data = Object.assign({}, this.nameModel)
      updateUser(data).then((res) => {
        if (res.code == 1) {
          this.$message.success('保存成功')
           this.nameDialogFormVisible = false
          this.handleFilter()
         
        }
      })
    },
    // 开关
    onOff(row) {
      console.log(row, !row.status)
      this.$confirm('此操作会更改该账户状态，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let status = ''
          if (row.status == 0) {
            status = 1
          } else {
            status = 0
          }
          lock({
            userId: row.userId,
            status: status
          }).then((res) => {
            if (res.code) {
              this.$message.success('操作成功')
              this.getList()
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    changePasswordState() {
      this.passwordState = !this.passwordState
    }
  }
}
</script>

<style scoped>
</style>
